package org.example.oop.io_stream;

import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * org.example.oop.serial
 *
 * @author moLei
 * @description 序列化
 * @since 2025/6/20
 */
@Slf4j
@ToString
public class SerializableDemo implements Serializable {

    /**
     * 序列化码，如果修改了类，则需要重新生成，不然不够准确，根据类代码进行计算的。反序列化时候会用到。UID不一样则反序列化失败
     */
    private static final long serialVersionUID = -6936315112771390342L;

    private String name;

    private String age;

    /**
     * transient修饰的变量不会被序列化
     */
    private transient String sex ;

    public static void serialObj() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("serializable.txt"));
             ObjectInputStream ois = new ObjectInputStream(new FileInputStream("serializable.txt"));) {
            SerializableDemo serializableDemo = new SerializableDemo();
            serializableDemo.age = "10";
            serializableDemo.name = "moLei";
            serializableDemo.sex = "男";
            oos.writeObject(serializableDemo);
            SerializableDemo sd = (SerializableDemo) ois.readObject();
            log.info("反序列化对象：{}", sd);
        } catch (Exception e) {
            log.error("文件操作异常：{}", e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        serialObj();
    }


}
